// 文章服务层

import { Op, fn, col } from 'sequelize'
import { Article, User, Comment } from '../models/index.js'
import { ArticleTypes } from '../types/index.js'
import { validatePagination } from '../utils/validation.js'

/**
 * 创建文章
 */
const createArticle = async (articleData, userId) => {
  const article = await Article.create({
    ...articleData,
    authorId: userId,
    status: ArticleTypes.STATUS.PUBLISHED
  })
  
  return article
}

/**
 * 获取文章列表
 */
const getArticles = async (options = {}) => {
  const { page = 1, limit = 10, category, search } = options
  const { page: pageNum, limit: limitNum } = validatePagination(page, limit)
  
  const where = {}
  
  if (category) {
    where.category = category
  }
  
  if (search) {
    where[Op.or] = [
      { title: { [Op.like]: `%${search}%` } },
      { content: { [Op.like]: `%${search}%` } }
    ]
  }
  
  const { count, rows } = await Article.findAndCountAll({
    where,
    include: [
      {
        model: User,
        as: 'author',
        attributes: ['id', 'username', 'avatar']
      }
    ],
    order: [['createdAt', 'DESC']],
    limit: limitNum,
    offset: (pageNum - 1) * limitNum
  })
  
  return {
    articles: rows,
    pagination: {
      currentPage: pageNum,
      totalPages: Math.ceil(count / limitNum),
      totalItems: count,
      pageSize: limitNum
    }
  }
}

/**
 * 获取文章详情
 */
const getArticleById = async (articleId) => {
  const article = await Article.findByPk(articleId, {
    include: [
      {
        model: User,
        as: 'author',
        attributes: ['id', 'username', 'avatar', 'title', 'bio']
      },
      {
        model: Comment,
        as: 'comments',
        include: [
          {
            model: User,
            as: 'author',
            attributes: ['id', 'username', 'avatar']
          }
        ],
        order: [['createdAt', 'DESC']]
      }
    ]
  })
  
  if (!article) {
    throw new Error('文章不存在')
  }
  
  // 增加浏览量
  await article.increment('views')
  
  return article
}

/**
 * 获取我的文章
 */
const getMyArticles = async (userId) => {
  const articles = await Article.findAll({
    where: { authorId: userId },
    include: [
      {
        model: User,
        as: 'author',
        attributes: ['id', 'username', 'avatar']
      }
    ],
    order: [['createdAt', 'DESC']]
  })
  
  return articles
}

/**
 * 更新文章
 */
const updateArticle = async (articleId, updateData, userId) => {
  const article = await Article.findOne({
    where: { id: articleId, authorId: userId }
  })
  
  if (!article) {
    throw new Error('文章不存在或无权限修改')
  }
  
  await article.update(updateData)
  
  return article
}

/**
 * 删除文章
 */
const deleteArticle = async (articleId, userId) => {
  const article = await Article.findOne({
    where: { id: articleId, authorId: userId }
  })
  
  if (!article) {
    throw new Error('文章不存在或无权限删除')
  }
  
  await article.destroy()
  
  return true
}

/**
 * 创建评论
 */
const createComment = async (articleId, commentData, userId) => {
  const article = await Article.findByPk(articleId)
  
  if (!article) {
    throw new Error('文章不存在')
  }
  
  const comment = await Comment.create({
    ...commentData,
    articleId,
    authorId: userId
  })
  
  return comment
}

/**
 * 获取文章统计
 */
const getArticleStats = async (userId) => {
  const stats = await Article.findAll({
    where: { authorId: userId },
    attributes: [
      [fn('COUNT', col('id')), 'totalArticles'],
      [fn('SUM', col('views')), 'totalViews'],
      [fn('SUM', col('likes')), 'totalLikes']
    ],
    raw: true
  })
  
  return {
    totalArticles: parseInt(stats[0]?.totalArticles || 0),
    totalViews: parseInt(stats[0]?.totalViews || 0),
    totalLikes: parseInt(stats[0]?.totalLikes || 0)
  }
}

export default {
  createArticle,
  getArticles,
  getArticleById,
  getMyArticles,
  updateArticle,
  deleteArticle,
  createComment,
  getArticleStats
} 